package com.caocaog.market.handler;

import com.caocaog.market.entity.dto.PushStatisticDTO;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.jeecg.common.exception.TypeConversionException;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class PushStatisticHandler extends BaseTypeHandler<PushStatisticDTO> {

    private static final ObjectMapper MAPPER = new ObjectMapper();

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int columnIndex, PushStatisticDTO pushStatisticDTO, JdbcType jdbcType) throws SQLException {
        try {
            preparedStatement.setString(columnIndex, MAPPER.writeValueAsString(pushStatisticDTO));
        } catch (JsonProcessingException e) {
            throw new TypeConversionException(e.getMessage());
        }
    }

    @Override
    public PushStatisticDTO getNullableResult(ResultSet resultSet, String columnName) throws SQLException {
        String value = resultSet.getString(columnName);
        if (value == null) return new PushStatisticDTO();
        try {
            return MAPPER.readValue(value, PushStatisticDTO.class);
        } catch (JsonProcessingException e) {
            throw new TypeConversionException(e.getMessage());
        }
    }

    @Override
    public PushStatisticDTO getNullableResult(ResultSet resultSet, int columnIndex) throws SQLException {
        String value = resultSet.getString(columnIndex);
        if (value == null) return new PushStatisticDTO();
        try {
            return MAPPER.readValue(value, PushStatisticDTO.class);
        } catch (JsonProcessingException e) {
            throw new TypeConversionException(e.getMessage());
        }
    }

    @Override
    public PushStatisticDTO getNullableResult(CallableStatement callableStatement, int columnIndex) throws SQLException {
        String value = callableStatement.getString(columnIndex);
        if (value == null) return new PushStatisticDTO();
        try {
            return MAPPER.readValue(value, PushStatisticDTO.class);
        } catch (JsonProcessingException e) {
            throw new TypeConversionException(e.getMessage());
        }
    }
}
